/**************************************************************************************************

	NSurvey - The web survey and form engine
	Copyright (c) 2004, Thomas Zumbrunn. (http://www.nsurvey.org)

	Dotnetnuke PA module 
	Copyright (c) 2004, Oliver Hine (oliver.hine@gmail.com)

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


************************************************************************************************/
using DotNetNuke;
using Microsoft.VisualBasic;
using MetaBuilders.WebControls;
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Votations.NSurvey.BusinessRules;
using Votations.NSurvey.DataAccess;
using Votations.NSurvey.Data;
using Votations.NSurvey.WebAdmin.UserControls;
using Votations.NSurvey.Enums;
using Votations.NSurvey.Web;

namespace Votations.NSurvey.WebAdmin
{
	public class EditSingleQuestion : PageBase
	{
		protected System.Web.UI.WebControls.Label MessageLabel;
		protected System.Web.UI.WebControls.DropDownList SelectionModeDropDownList;
		protected System.Web.UI.WebControls.DropDownList DisplayModeDropDownList;
		protected System.Web.UI.WebControls.Button UpdateQuestionButton;
		protected System.Web.UI.WebControls.DropDownList MinSelectionDropDownList;
		protected System.Web.UI.WebControls.DropDownList MaxAllowedDropDownList;
		protected System.Web.UI.WebControls.CheckBox RandomizeCheckBox;
		protected System.Web.UI.WebControls.CheckBox RatingCheckbox;
		protected System.Web.UI.WebControls.PlaceHolder AnswerOptionsPlaceholder;
		protected DotNetNuke.UI.UserControls.TextEditor QuestionFreeTextBox;
		protected System.Web.UI.WebControls.DropDownList ColumnDropdownlist;
		protected System.Web.UI.WebControls.Literal EditQuestionTitle;
		protected System.Web.UI.WebControls.Literal SelectionModeLabel;
		protected System.Web.UI.WebControls.Literal DisplayModeLabel;
		protected System.Web.UI.WebControls.Literal ColumnNumberLabel;
		protected System.Web.UI.WebControls.Literal RandomizeAnswersLabel;
		protected System.Web.UI.WebControls.Literal AnswerRatingLabel;
		protected System.Web.UI.WebControls.Literal MinSelectionLabel;
		protected System.Web.UI.WebControls.Literal MaxSelectionAllowed;
		protected System.Web.UI.WebControls.Button EditAnswersButton;
		protected System.Web.UI.WebControls.Literal QuestionPipeAliasLabel;
		protected System.Web.UI.WebControls.TextBox PipeAliasTextBox;
		protected System.Web.UI.WebControls.Button ExportXMLButton;

		protected HeaderControl Header;

		protected bool MultipleSelection
		{
			get { return (bool)ViewState["MultipleSelection"]; }
			set { ViewState["MultipleSelection"] = value; }
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.RatingCheckbox.CheckedChanged += new System.EventHandler(this.RatingCheckbox_CheckedChanged);
			this.UpdateQuestionButton.Click += new System.EventHandler(this.UpdateQuestionButton_Click);
			this.EditAnswersButton.Click += new System.EventHandler(this.EditAnswersButton_Click);
			this.ExportXMLButton.Click += new System.EventHandler(this.ExportXMLButton_Click);
			this.Load += new System.EventHandler(this.Page_Load);
		}
		#endregion

		private void Page_Load(object sender, System.EventArgs e)
		{
			try
			{
				SetupSecurity();
				LocalizePage();

				ValidateRequestQuestionId();
				MessageLabel.Visible = false;
				if (!Page.IsPostBack)
				{
					Header.SurveyId = SurveyId;
					FillDefaultFields();
					BindQuestionOptions();
				}
			}
			catch( Exception exc)
			{
				DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this,exc);
			}
		}

		private void SetupSecurity()
		{
			CheckRight(NSurveyRights.AccessFormBuilder, true);
		}

		private void LocalizePage()
		{
			EditQuestionTitle.Text = GetPageResource("EditQuestionTitle");
			SelectionModeLabel.Text = GetPageResource("SelectionModeLabel");
			DisplayModeLabel.Text = GetPageResource("DisplayModeLabel");
			ColumnNumberLabel.Text = GetPageResource("ColumnNumberLabel");
			RandomizeAnswersLabel.Text = GetPageResource("RandomizeAnswersLabel");
			AnswerRatingLabel.Text = GetPageResource("AnswerRatingLabel");
			MinSelectionLabel.Text = GetPageResource("MinSelectionLabel");
			MaxSelectionAllowed.Text = GetPageResource("MaxSelectionAllowed");
			UpdateQuestionButton.Text = GetPageResource("UpdateQuestionButton");
			EditAnswersButton.Text = GetPageResource("EditAnswersButton");
			QuestionPipeAliasLabel.Text = GetPageResource("QuestionPipeAliasLabel");
			ExportXMLButton.Text = GetPageResource("ExportXMLButton");

			if (!Page.IsPostBack)
			{
				ColumnDropdownlist.Items.Insert(0, new ListItem(GetPageResource("NoSelectionRequiredOption"),"0"));
				MinSelectionDropDownList.Items.Insert(0, new ListItem(GetPageResource("NoSelectionRequiredOption"),"0"));
				MaxAllowedDropDownList.Items.Insert(0, new ListItem(GetPageResource("UnlimitedSelectionOption"),"0"));
			}
		}
	

		private void ValidateRequestQuestionId()
		{
			_questionId = 
				Information.IsNumeric(Request["QuestionId"]) ? int.Parse(Request["QuestionId"]) : -1;
			
			if (_questionId != -1 && !NSurveyUser.Identity.IsAdmin &&
				!NSurveyUser.Identity.HasAllSurveyAccess)
			{
				if (!new Question().CheckQuestionUser(_questionId, NSurveyUser.Identity.UserId))
				{
					_questionId = -1;
				}
			}

			if (_questionId == -1)
			{
				throw new FormatException("Invalid question id!");
			}		
		}

		/// <summary>
		/// Get the current DB stats and fill 
		/// the label with them
		/// </summary>
		private void FillDefaultFields()
		{
			DisplayModeDropDownList.DataSource = new Questions().GetQuestionLayoutModes();
			DisplayModeDropDownList.DataMember = "LayoutModes";
			DisplayModeDropDownList.DataTextField = "Description";
			DisplayModeDropDownList.DataValueField = "LayoutModeID";
			DisplayModeDropDownList.DataBind();
			TranslateListControl(DisplayModeDropDownList);

			SelectionModeDropDownList.DataSource = new Questions().GetSelectableQuestionSelectionModes();
			SelectionModeDropDownList.DataMember = "QuestionSelectionModes";
			SelectionModeDropDownList.DataTextField = "Description";
			SelectionModeDropDownList.DataValueField = "QuestionSelectionModeID";
			SelectionModeDropDownList.DataBind();
			TranslateListControl(SelectionModeDropDownList);
		}

		/// <summary>
		/// Set the forms to match DB question options
		/// </summary>
		private void BindQuestionOptions()
		{
			// Retrieve the original question values
			QuestionData question = new Questions().GetQuestionById(_questionId);
			QuestionData.QuestionsRow questionRow = question.Questions[0];

			// Assign them to the form
			QuestionFreeTextBox.Text = questionRow.QuestionText;
			DisplayModeDropDownList.SelectedValue = 
				(questionRow.IsLayoutModeIdNull()) ? ((int)QuestionLayoutMode.Horizontal).ToString() : questionRow.LayoutModeId.ToString();
			ColumnDropdownlist.SelectedValue = questionRow.ColumnsNumber.ToString();
			SelectionModeDropDownList.SelectedValue = questionRow.SelectionModeId.ToString();
			MinSelectionDropDownList.SelectedValue = 
				(questionRow.IsMinSelectionRequiredNull()) ? "0" : questionRow.MinSelectionRequired.ToString();
			MaxAllowedDropDownList.SelectedValue = 
				(questionRow.IsMaxSelectionAllowedNull()) ? "0" : questionRow.MaxSelectionAllowed.ToString();
		
			RandomizeCheckBox.Checked = questionRow.RandomizeAnswers;
			RatingCheckbox.Checked = questionRow.RatingEnabled;
			PipeAliasTextBox.Text = questionRow.QuestionPipeAlias;
			RandomizeCheckBox.Enabled = !RatingCheckbox.Checked;
			ViewState["LibraryId"] = questionRow.IsLibraryIdNull() ? -1 : questionRow.LibraryId;

			if (!questionRow.IsLibraryIdNull() && !NSurveyUser.Identity.IsAdmin)
			{
				CheckRight(NSurveyRights.ManageLibrary, true);
			}

			// Can the question have answers
			if (((QuestionTypeMode)questionRow.TypeMode & QuestionTypeMode.Answerable)>0)
			{
				AnswerOptionsPlaceholder.Visible = true;
				EditAnswersButton.Enabled = true;
				MultipleSelection = ((QuestionTypeMode)questionRow.TypeMode & QuestionTypeMode.MultipleAnswers)>0;
			}
			else
			{
				AnswerOptionsPlaceholder.Visible = false;
				EditAnswersButton.Enabled = false;
			}
		}

		private void UpdateQuestionButton_Click(object sender, System.EventArgs e)
		{
			if (QuestionFreeTextBox.Text.Length == 0)
			{
				MessageLabel.Visible = true;
				MessageLabel.Text = GetPageResource("MissingQuestionMessage");

			}
			else
			{
				// creates a BE and update the question
				QuestionData question = new QuestionData();
				QuestionData.QuestionsRow updatedQuestion = 
					question.Questions.NewQuestionsRow();

				// Set the updated fields
				updatedQuestion.QuestionId = _questionId;
				updatedQuestion.SurveyId = SurveyId;
				updatedQuestion.QuestionText = QuestionFreeTextBox.Text.Length > 3900 ?
					QuestionFreeTextBox.Text.Substring(0, 3900) : QuestionFreeTextBox.Text;
				updatedQuestion.ColumnsNumber = int.Parse(ColumnDropdownlist.SelectedValue);
				updatedQuestion.MinSelectionRequired = int.Parse(MinSelectionDropDownList.SelectedValue);
				updatedQuestion.MaxSelectionAllowed = int.Parse(MaxAllowedDropDownList.SelectedValue);
				updatedQuestion.LayoutModeId = int.Parse(DisplayModeDropDownList.SelectedValue);
				updatedQuestion.SelectionModeId = int.Parse(SelectionModeDropDownList.SelectedValue);
				updatedQuestion.RandomizeAnswers = RatingCheckbox.Checked ? false : RandomizeCheckBox.Checked;
				updatedQuestion.RatingEnabled = RatingCheckbox.Checked;
				updatedQuestion.QuestionPipeAlias = PipeAliasTextBox.Text;
				question.Questions.AddQuestionsRow(updatedQuestion);

				new Question().UpdateQuestion(question);

				MessageLabel.Visible = true;
				MessageLabel.Text = GetPageResource("OptionsUpdatedMessage");
			
				BindQuestionOptions();
			}
		}

		private void RatingCheckbox_CheckedChanged(object sender, System.EventArgs e)
		{
			// Disable random order option
			// if the rating choice has been checked
			RandomizeCheckBox.Enabled = !RatingCheckbox.Checked;
		}

		private void ExportXMLButton_Click(object sender, System.EventArgs e)
		{
			Response.Charset = "utf-8";
			Response.ContentType = "application/octet-stream";
			
			Response.ContentType = "text/xml";
			Response.AddHeader("Content-Disposition", "attachment; filename=\"nsurvey_question"+_questionId+".xml\"");

			NSurveyQuestion questionForm = new Questions().GetQuestionForExport(_questionId);
			questionForm.WriteXml(Response.OutputStream, System.Data.XmlWriteMode.IgnoreSchema);
			Response.End();
		}

		int _questionId;

		private void EditAnswersButton_Click(object sender, System.EventArgs e)
		{
			UINavigator.NavigateToSingleQuestionAnswersEdit(SurveyId, _questionId, (int)ViewState["LibraryId"], MenuIndex);
		}

	}
}
